/**
 * Created by icyhy on 2017/5/23.
 */
"use strict";
var builder = require("../response/rest.result.builder.js");
var docModel = require("../models/doc");
var userModel = require("../models/user");
var nodeWeixinExpressSession = require('node-weixin-express-session');

module.exports = {

  create : function (req, res, next) {
    var docEntity = new docModel(req.body);
    var userid = docEntity.userId;
    var clanid = docEntity.clanId;

    if(!clanid || clanid == ""){ //用户没有参加任何部落，提示用户去加入某个部落
      return builder.buildBadRequestResultWithMessage(res, "用户没有参加任何部落，请先参加部落");
    }
    //根据用户的id去寻找用户的clanid，如果用户没有参加任何部落，则提示需要先加入部落
    docEntity.userId = userid;
    docEntity.clanid = clanid;
    docModel.create(docEntity, function(err) {
      if (err) return next(err);
      return builder.buildSuccessResultInfo(res, docEntity);
    });
  },
  update: function(reg, res,next){
    var docEntity = new docModel(req.body);
    var id = docEntity.id;
    docModel.findOneAndUpdate({_id:id}, docEntity,{upsert:true},function(err){
      if(err) return next(err);
      return builder.buildSuccessResultInfo(res);
    });
  },
  getListByClan:function(req, res, next){
    var id = req.params.id || ''; //部落id
    docModel.find({
      'clanId': id
    })
      .exec(function(err, records) {
        if (err) return next(err);
        if (!records) return next(new Error('not  found'));

        return builder.buildSuccessResultInfoWithData(res, records);
      });
  },
  getListByUser:function(req, res, next){
    var id = req.params.id || ''; //用户id
    docModel.find({
      'userId': id
    })
      .exec(function(err, records) {
        if (err) return next(err);
        if (!records) return next(new Error('not  found'));

        return builder.buildSuccessResultInfoWithData(res, records);
      });
  },
  getById:function(req, res, next){
    var id = req.params.id || '';
    console.log( req.params.id);
    docModel.findOne({
      _id: id
    })
      .exec(function(err, record) {
        if (err) return next(err);
        if (!record) return next(new Error('not  found'));
        return builder.buildSuccessResultInfoWithData(res, record);
      });
  },
  deleteById:function (req, res, next) {
    var id = req.params.id || ''; //素材id
    docModel.remove({ _id: id }, function (err) {
      if (err) return next(err);
      return builder.buildSuccessResultInfo(res);
    });
  },
}
